package net.zjitc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.zjitc.common.CustomException;
import net.zjitc.dto.SetMealDto;
import net.zjitc.entity.SetMeal;
import net.zjitc.entity.SetMealDish;
import net.zjitc.mapper.SetMealMapper;
import net.zjitc.service.SetMealDishService;
import net.zjitc.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal> implements SetMealService {
    @Autowired
    private SetMealDishService setMealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetMealDto setMealDto) {
        this.save(setMealDto);

        List<SetMealDish> setmealDishes = setMealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setMealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setMealDishService.saveBatch(setmealDishes);
    }

    @Transactional
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<SetMeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetMeal::getId,ids);
        wrapper.eq(SetMeal::getStatus,1);
        int count=this.count(wrapper);
        if(count>0){
            throw new CustomException("套餐正在售卖,不能删除");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetMealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetMealDish::getSetmealId,ids);
        setMealDishService.remove(queryWrapper);
    }

    @Override
    @Transactional
    public void updateWithDish(SetMealDto setmealDto) {
        this.updateById(setmealDto);
        LambdaQueryWrapper<SetMealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetMealDish::getSetmealId,setmealDto.getId());
        setMealDishService.remove(wrapper);
        List<SetMealDish> list = setmealDto.getSetmealDishes();
        for (SetMealDish s:list){
            s.setSetmealId(setmealDto.getId());
        }
        setMealDishService.saveBatch(list);
    }
}
